import { __isObject } from "./utils";

const effectMap = new WeakMap();
// obj 是不同对象，name是对象的属性。也就是基于effect-v2再封装一层对象
// WeakMap
// {
//   obj: Map
//         {
//           name: Set
//                 [fn1, fn2]
//         }
// }

let activeEffect = null;

// 收集依赖
const track = (target, key) => {
  if (!activeEffect) return;
  console.log(12, target);
  
  let objMap = effectMap.get(target);

  if (!objMap) {
    effectMap.set(target, new Map());
  }
  objMap = effectMap.get(target);
  let keySet = objMap.get(key);
  if (!keySet) {
    objMap.set(key, new Set());
  }
  keySet = objMap.get(key);
  keySet.add(activeEffect);
};

// 触发依赖
const trigger = (target, key) => {
  let objMap = effectMap.get(target);
  if (!objMap) return;
  let keySet = objMap.get(key);
  if (!keySet) return;
  keySet.forEach((fn) => fn());
};

function reactive(obj) {
  return new Proxy(obj, {
    get(target, prop) {
      track(target, prop);
      return target[prop];
    },
    set(target, prop, value) {
      if (__isObject(value)) {
        target[prop] = reactive(value);
      } else {
        target[prop] = value;
      }

      trigger(target, prop);
      return true;
    },
  });
}

const effect = (fn) => {
  if (typeof fn !== "function") {
    return;
  }

  activeEffect = fn;
  fn();
  activeEffect = null;
};

export { effect, reactive, effectMap };
